var express = require('express');
var router = express.Router();
var { userModel, branchModel } = require('../model/models')
var jwt = require('jsonwebtoken')
var multiparty = require('multiparty')

var { sendMails } = require('../model/qq')

const tencentcloud = require("tencentcloud-sdk-nodejs");
// 人脸
const IaiClient = tencentcloud.iai.v20200303.Client;
const clientConfig = {
  credential: {
    secretId: "AKIDGNHzUlodDYfZNxLekeKmW4NSJelfKm0z",
    secretKey: "nMglbGsGUVM2Uhrpb9TZS7ckeNuJYcU8",
  },
  region: "ap-shanghai",
  profile: {
    httpProfile: {
      endpoint: "iai.tencentcloudapi.com",
    },
  },
};
const client = new IaiClient(clientConfig);
// 登录
router.post('/login', async (req, res) => {
  const body = req.body;
  let user = await userModel.findOne({ $and: [{ phone: body.phone }, { password: body.password }] }).populate('b_id').lean().exec()
  if (!user) {
    res.send({
      code: 402,
      mag: '该用户不存在'
    })
    return
  }
  if (!user.b_id) {
    const breach = await branchModel.find({ responsible: user._id }).lean().exec()
    user.b_id = breach
    user.responsible = breach.length > 0 ? 1 : 0
  } else {
    user.responsible = 0
  }
  let id = { id: user._id }
  if (user.face) {
    res.send({
      code: 200,
      msg: '登录成功',
      id
    })
  } else {
    let id = { user: user._id }
    const token = jwt.sign(id, 'flag')
    res.send({
      code: 200,
      msg: '登录成功',
      token,
      user
    })
  }
})
// 人脸登录
router.post('/face', async (req, res) => {
  const body = req.body;
  var user = await userModel.findOne({ _id: body.id }).populate('b_id').lean().exec()
  // 人脸比对
  const params = {
    "ImageA": user.face,
    "ImageB": body.face,
  };
  client.CompareFace(params).then(
    async (data) => {
      if (!user.b_id) {
        const breach = await branchModel.find({ responsible: user._id }).lean().exec()
        user.b_id = breach
        user.responsible = breach.length > 0 ? 1 : 0
      } else {
        user.responsible = 0
      }
      let id = { user: body.id }
      const token = jwt.sign(id, 'flag')
      res.send({
        code: 200,
        msg: '登录成功',
        token,
        user
      })
    },
    (err) => {
      res.send({
        code: 400,
        msg: err,
      })
    }
  )
})
// 创建验证码
let getVerificationCode = (codeLength = 4) => { //传入需要的字符串长度，不传默认为4
  // 准备一个用来抽取码的字符串，或者字典
  // let verification_code_str = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  //数字和字母
  let verification_code_str = "0123456789";     //纯数字
  // 获取某个范围的随机整数，封装的函数，在上面抽取字典的时候进行了调用
  function getRandom(min, max) {                 //意思是获取min-max数字之间的某个随机数，直接调用即可
    return Math.round(Math.random() * (max - min) + min);
  }
  let newStr = '';                    //创建一个空字符串，用来拼接四位随机码
  for (var i = 0; i < codeLength; i++) {       //for循环四次，则拼接四次随机码
    newStr += verification_code_str[getRandom(0, verification_code_str.length - 1)];   //从字典中随机选一个下标，并拼接到空字符串中
  }
  return newStr
}
 
// 发送验证码
router.post('/code', (req,res) => {
  const body = req.body
  let mailId = body.email
  let VerificationCode = getVerificationCode()
  sendMails(mailId, VerificationCode).then(resa => {
    // console.log(res, '返回的数据');
    let istrue = false
    if (resa.response == '250 OK: queued as.') {             //如果发送成功执行的操作
        istrue = true
    }
    if(istrue){
      res.send({
        code:200,
        id:VerificationCode
       })
    }else{
      res.send({
        code:201
      })   
    }
  })
})

// 注册
router.post('/register', async (req, res) => {
  const body = req.body
  await userModel.create(body)
  res.send({
    code: 200,
    msg: '注册成功'
  })
})

// 添加头像
router.post('/upload', async (req, res) => {
  // var form = new multiparty.Form()
  // let id = req.user.user
  // form.uploadDir = 'upload'
  // form.parse(req, async (err, data, file) => {
  //   let url = 'https://ihrms.lyc.husf.xyz/' + file.file[0].path
  //   // let url = 'http://127.0.0.1:3000/'+file.file[0].path
  //   await userModel.updateOne({ _id: id }, { header: url })
  //   let user = await userModel.findOne({ _id: id }).lean().exec()
  //   if (!user.b_id) {
  //     const breach = await branchModel.find({ responsible: user._id }).lean().exec()
  //     user.b_id = breach
  //     user.responsible = breach.length > 0 ? 1 : 0
  //   } else {
  //     user.responsible = 0
  //   }
  //   res.send({
  //     user
  //   })
  // })
  res.send({
    code:200
  })
})
module.exports = router;
